﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace PPIDesktopClient.General
{
    public class DirHelper
    {
        #region Protected Members
        protected string m_NewDirectory;
        protected string m_SelectedDirectory;
        protected string m_OutboxDirectory;
        protected string m_SdfPath;
        protected string m_ImagesFolder;
        #endregion

        #region Public Members
        public string ImagesFolder
        {
            get { return m_ImagesFolder; }
        }
        public string SdfPath
        {
            get { return m_SdfPath; }

        }
        public string NewDirectory
        {
            get { return m_NewDirectory; }
        }
        #endregion

        /// <summary>
        /// Create new directory in Outbox folder is necesary and copy the download images
        /// </summary>
        /// <param name="SelectedDirectory"></param>
        /// <param name="SDFPath">path to sdf database</param>
        public DirHelper(string SelectedDirectory, string SDFPath)
        {
            this.m_SelectedDirectory = SelectedDirectory;
            this.m_OutboxDirectory = Constants.K_OutboxPath;
            this.m_SdfPath = SDFPath;
            CreateNewDirectory();
            CopyImagesToNewDirectory();
        }
        protected void CreateNewDirectory()
        {
            DirectoryInfo _Dir = null;
            try
            {
                if (isDirectory(m_OutboxDirectory))
                    _Dir = Directory.CreateDirectory(m_OutboxDirectory).CreateSubdirectory(DateTime.Now.Ticks.ToString());
                m_NewDirectory = _Dir.FullName;
            }
            catch (Exception)
            {

                throw;
            }
        }
        protected void CopyImagesToNewDirectory()
        {
            try
            {
                DirectoryInfo _dir = new DirectoryInfo(m_SelectedDirectory);
                DirectoryInfo _newDir = new DirectoryInfo(m_NewDirectory);
                CopyFiles(_dir, _newDir, true);
                m_SdfPath = GetSdfPath(_newDir.FullName);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// return full sdf path
        /// </summary>
        /// <param name="Folder"></param>
        /// <returns></returns>
        public static string GetSdfPath(string Folder)
        {
            try
            {
                DirectoryInfo _d = new DirectoryInfo(Folder);
                FileInfo[] _Files = _d.GetFiles("*.sdf");
                if (_Files.Length > 0)
                    return _Files[0].FullName;
                return "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Copy files and folders  in  recursive action
        /// </summary>
        /// <param name="diSource">Source Directory</param>
        /// <param name="diDestination">Destination Directory</param>
        /// <param name="blOverwrite">overwrite: True, False</param>
        public static void CopyFiles(DirectoryInfo diSource, DirectoryInfo diDestination, bool blOverwrite)
        {
            DirectoryInfo[] diSourceSubDirectories;
            FileInfo[] fiSourceFiles;

            //obtengo todos los archivos del directorio origen
            fiSourceFiles = diSource.GetFiles();
            //obtengo los subdirectorios (si existen)
            diSourceSubDirectories = diSource.GetDirectories();

            //si no existe el directorio destino crearlo
            if (!diDestination.Exists) diDestination.Create();

            //Usar la recursividad para navegar por los subdirectorios
            //e ir obteniendo los archivos hasta llegar al final
            foreach (DirectoryInfo diSourceSubDirectory in diSourceSubDirectories)
            {
                CopyFiles(diSourceSubDirectory, new DirectoryInfo(diDestination.FullName + "\\" +
                  diSourceSubDirectory.Name), blOverwrite);
            }

            foreach (FileInfo fiSourceFile in fiSourceFiles)
            {
                if (fiSourceFile.Extension != "xml")
                {
                    fiSourceFile.CopyTo(diDestination.FullName + "\\" + fiSourceFile.Name, blOverwrite);
                }
            }
        }

        /// <summary>
        /// check and create if the directory exist
        /// </summary>
        /// <param name="_directory"></param>
        /// <returns>true if exist, false is created</returns>
        public static bool isDirectory(string _directory)
        {
            bool _exists = false;
            if (!Directory.Exists(_directory))
                Directory.CreateDirectory(_directory);
            else
                _exists = true;
            return _exists;

        }

        /// <summary>
        /// Delete directory files
        /// </summary>
        /// <param name="_TempPhotoDirectory">directory fullpath</param>
        public static void CleanDirectory(string _TempPhotoDirectory)
        {
            isDirectory(_TempPhotoDirectory);
            DeleteFiles(new DirectoryInfo(_TempPhotoDirectory));
        }
        private static int FindFolder(List<string> FoldersToMoveAfterUpload, string Folder)
        {
            for (int _Position = 0; _Position < FoldersToMoveAfterUpload.Count; _Position++)
            {
                if (FoldersToMoveAfterUpload[_Position] == Folder)
                    return _Position;
            }
            return -1;
        }
        /// <summary>
        /// Get the next directory to upload information via webservice.
        /// </summary>
        /// <param name="_Dir"></param>
        /// <returns></returns>
        public static string getNextDirectory(string Dir, List<string> FoldersToMoveAfterUpload)
        {
            DirectoryInfo OutboxDir = new DirectoryInfo(Dir);
            DirectoryInfo[] _Childs = OutboxDir.Parent.GetDirectories();
            Array.Sort(_Childs, new DirectorySort());
            foreach (DirectoryInfo _Child in _Childs)
            {
                if (FindFolder(FoldersToMoveAfterUpload, _Child.FullName) == -1)
                    return _Child.FullName;
            }
            return "";
        }

        public static void DeleteFiles(DirectoryInfo _dir)
        {
            FileInfo[] _files = _dir.GetFiles();
            foreach (FileInfo _file in _files)
            {
                _file.Delete();
            }
        }

        public static string CreateVisitDirectory(int structureID, string imageFolder)
        {
            int Start = 0;
            int End = 99;
            string _Directory = "";
            bool _FoundPosition = false;
            try
            {
                while (!_FoundPosition)
                {
                    if (structureID > Start && structureID > End)
                    {
                        Start += 100;
                        End += 100;
                    }
                    else
                    {
                        _FoundPosition = true;
                        _Directory = Start.ToString() + "-" + End.ToString();
                        DirHelper.isDirectory(imageFolder + _Directory);
                        _Directory = imageFolder + _Directory;
                    }
                }
                return _Directory;
            }
            catch (IOException ioex)
            {
                ErrorManager.Log("IOException", "CreateVisitDirectory " + ioex.TargetSite, ioex.Message, ioex.StackTrace);
                return null;
            }
        }

        public static string GetImagesDirectory(string connectionString)
        {
            string returnPath = "";
            if (connectionString != null)
            {
                DirectoryInfo _ConnectionDirectory = new DirectoryInfo(connectionString);
                DirectoryInfo[] _ImagesDirectory = _ConnectionDirectory.Parent.GetDirectories("Images");
                if (_ImagesDirectory.Length > 0)
                    returnPath = _ImagesDirectory[0].FullName;
            }
            return returnPath;

        }


        public static string GetImageDirectory(string imageDir, int assetId, int imageId ,bool createFolder)
        {
            int Start = 0;
            int End = 99;
            string _Directory = "";
            bool _FoundPosition = false;
            while (!_FoundPosition)
            {
                if (assetId > Start && assetId > End)
                {
                    Start += 100;
                    End += 100;
                }
                else
                {
                    _FoundPosition = true;
                    _Directory = Start.ToString() + "-" + End.ToString();
                    _Directory = imageDir + _Directory;
                    if(createFolder)
                    {
                        if (!Directory.Exists(_Directory))
                            Directory.CreateDirectory(_Directory);
                    }
                }
                _Directory += "\\" + assetId + "_" + imageId + ".jpg";
            }
            return _Directory;
        }
    }
    public class DirectorySort : IComparer
    {
        public int Compare(object x, object y)
        {
            DirectoryInfo d1 = (DirectoryInfo)x;
            DirectoryInfo d2 = (DirectoryInfo)y;
            return long.Parse(d1.Name).CompareTo(long.Parse(d2.Name));
        }
    }

}
